package com.wds.controller;

import com.wds.common.annotation.SystemLog;
import com.wds.common.utils.BeanCopyUtils;
import com.wds.common.utils.SecurityUtils;
import com.wds.domain.JsonResult;
import com.wds.domain.dto.UserLoginDto;
import com.wds.domain.entity.User;
import com.wds.domain.vo.RoutersVo;
import com.wds.domain.vo.UserInfoVo;
import com.wds.domain.vo.UserVo;
import com.wds.exception.CustomException;
import com.wds.service.AdminAuthenticationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-23 18:40
 */
@RestController
@Api(tags = "后台认证相关接口")
public class AdminLoginController {

    @Autowired
    private AdminAuthenticationService authenticationService;


    @SystemLog(businessName = "请求登录认证")
    @PostMapping("/user/login")
    @ApiOperation("登录")
    public JsonResult<Object> login(@RequestBody UserLoginDto dto) {
        User user = new User();

        user.setUsername(dto.getUserName());
        user.setPassword(dto.getPassword());

        // 用户名密码为空的情况
        if (!StringUtils.hasText(user.getUsername()) || !StringUtils.hasText(user.getPassword())) {
            throw new CustomException("请检查用户名和密码");
        }
        return authenticationService.login(user);
    }

    @PostMapping("/user/logout")
    public JsonResult<Object> logout() {
        return authenticationService.logout();
    }

    @GetMapping("/getInfo")
    public JsonResult<UserInfoVo> getInfo() {
//        获取当前用户
        User currentUser = SecurityUtils.getCurrentUser();
//         构建结果对象
        UserInfoVo infoVo = new UserInfoVo();
//        获取权限信息
        List<String> permissions = authenticationService.getPermissions(currentUser.getId());
        infoVo.setPermission(permissions);
//        获取角色信息
        List<String> roles = authenticationService.getRoles(currentUser.getId());
        infoVo.setRoles(roles);

//        获取用户信息
        infoVo.setUser(BeanCopyUtils.copy(currentUser, UserVo.class));

        return JsonResult.ok(infoVo);
    }

    @GetMapping("/getRouters")
    public JsonResult<RoutersVo> getRouters(){
        Long id = SecurityUtils.getCurrentUser().getId();
        return authenticationService.getRouters(id);
    }
}
